#-*- coding: UTF-8 -*-

from futu import *
import pandas as pd
import time
import  logging


class tradeapi():

    def __init__(self):
        self.tablename = "accinfo"
        self.host = '127.0.0.1'
        self.port = 11111
        self.password_md5 ='d6d1d2b50655a964810ba5592c9200a5'
    
    def _init_context(self, market, trd_env=TrdEnv.SIMULATE):
        
        self.trd_env = trd_env
        
        if market == 'HK':
            self.context = OpenHKTradeContext(host=self.host, port=self.port, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
            self.currency = Currency.HKD
            self.acc_id = '281756455983050852'
        elif market == 'A':
            self.context = OpenCNTradeContext(host=self.host, port=self.port, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
            self.currency = Currency.CNY 
        elif market == 'hkcc':
            self.context = OpenHKCCTradeContext(host=self.host, port=self.port, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
            self.currency = Currency.CNY
        elif market == 'FUTURE':
            self.context = OpenFutureTradeContext(host=self.host, port=self.port, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
            self.currency = Currency.CNY
        elif market == 'US':
            self.context = OpenUSTradeContext(host=self.host, port=self.port, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
            self.currency = Currency.USD
            self.acc_id = '281756460278018148'
        else:
            pass
            #except('错误的市场类型')
            
    def InitLogConfig(self, filepath = '../logs/futu_trade.log' ):
        logging.basicConfig(filename=filepath,format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level = logging.DEBUG,filemode='a',datefmt='%Y-%m-%d%I:%M:%S %p')

        
    def unlock_trade(self):
        self.context.unlock_trade(password_md5=self.password_md5, is_unlock=True)
        
    def closecontext(self):
        return self.context.close()
                
    def query_asset(self,acc_id=0, acc_index=0, refresh_cache=False ):
        return self.context.accinfo_query(self.trd_env, acc_id, acc_index, refresh_cache, currency=self.currency)
            
            
    # TrdSide:    BUY   SELL  SELL_SHORT  BUY_BACK 
    #TrdEnv: SIMULATE  REAL    OrderType: NORMAL MARKET  SPECIAL_LIMIT_ALL
    # '00700.HK' 
    
    def placeorder(self, price, qty, code, trd_side,  order_type=OrderType.NORMAL, remark = 'auto',fill_outside_rth=True ):
       # place_order(price, qty, code, trd_side, order_type=OrderType.NORMAL, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, remark=None, time_in_force=TimeInForce.DAY, fill_outside_rth=False)
        return self.context.place_order(price,qty,code,trd_side,order_type =order_type,trd_env = self.trd_env, remark=remark,fill_outside_rth=fill_outside_rth )
    
    #ModifyOrderOp.CANCEL
    # modify_order(modify_order_op, order_id, qty, price, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0)
    def modify_order(self, modify_order_op, order_id, qty, price, adjust_limit=0, acc_id=0, acc_index=0):
        
        return self.context.modify_order(modify_order_op, order_id, qty, price,
                                         adjust_limit=adjust_limit, acc_id=acc_id, acc_index=acc_index,trd_env = self.trd_env )
        
    
    #cancel_all_order(trd_env=TrdEnv.REAL, acc_id=0, acc_index=0)
    
    #position_list_query(code='', pl_ratio_min=None, pl_ratio_max=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False)
    def query_position(self,code='', pl_ratio_min=None, pl_ratio_max=None, acc_id=0, acc_index=0, refresh_cache=False):
        return self.context.position_list_query(code, pl_ratio_min, pl_ratio_max,self.trd_env, acc_id, acc_index,refresh_cache)
        
    #order_list_query(order_id="", status_filter_list=[], code='', start='', end='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False)
    def query_orders(self,order_id="", status_filter_list=[], code='', start='', end='', acc_id=0, acc_index=0, refresh_cache=False):
        return self.context.order_list_query(order_id,status_filter_list,code, start, end,self.trd_env, acc_id, acc_index, refresh_cache )
        
    #deal_list_query(code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False)
    def query_executions(self,code="", acc_id=0, acc_index=0, refresh_cache=False):
        return self.context.deal_list_query(code, self.trd_env, acc_id, acc_index, refresh_cache)
    
        
        